package com.evan.kdl.test.day01;

import com.evan.kdl.util.CommonUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * `CompletableFuture.allOf()`用于以下情形中：有多个需要独立并行运行的`Future`，并在所有这些`Future` 都完成后执行一些操作。
 */
public class AllOfDemo {

    public static CompletableFuture<String> readFileFuture(String fileName) {
        return CompletableFuture.supplyAsync(() -> {
            String content = CommonUtils.readFile(fileName);
            return content;
        });
    }

    public static void main(String[] args) {
        //    需求：统计news1.txt、new2.txt、new3.txt 文件中包含CompletableFuture关键字的文件的个数
        List<String> fileList = Arrays.asList("F:\\idea-workspace-personal\\juc-springboot-demo\\src\\main\\resources\\news1.txt",
                "F:\\idea-workspace-personal\\juc-springboot-demo\\src\\main\\resources\\news2.txt",
                "F:\\idea-workspace-personal\\juc-springboot-demo\\src\\main\\resources\\news3.txt");
        List<CompletableFuture<String>> readFileFutureList = fileList.stream().map(AllOfDemo::readFileFuture).collect(Collectors.toList());
        int len = readFileFutureList.size();
        CompletableFuture[] readFileFutureArr = readFileFutureList.toArray(new CompletableFuture[len]);

        CompletableFuture<Void> allOfFuture = CompletableFuture.allOf(readFileFutureArr);
        CompletableFuture<Long> countFuture = allOfFuture.thenApply(a -> readFileFutureList.stream()
                .map(CompletableFuture::join)
                .filter(s -> s.contains("CompletableFuture"))
                .count());
        Long count = countFuture.join();
        System.out.println("count = " + count);
    }
}